#include "gl_parser.h"
#include "gl_protocol.h"
#include "flash.h"

struct FLASH_STRUCT
{
    uint32_t size;
    uint32_t write_pos;
    uint32_t crc;
};

struct FLASH_STRUCT flash_s;

void parse_flash_frame(PARSE_STRUCT *parser_s)
{
    uint8_t error_code;
    FRAME_STRUCT frame_s;
    frame_s.Version = PROTOCOL_VERSION;
    frame_s.FrameDataLen = 0;
    frame_s.frame_data = NULL;
    frame_s.send_frame_fun = parser_s->frame_s.send_frame_fun;
    frame_s.MasterCmd = MASTER_CMD_FLASH;

    if(parser_s->frame_s.MasterCmd != MASTER_CMD_FLASH)
    {
        frame_s.SlaveCmd = SLAVE_CMD_FLASH_ERROR;
    }else{
        switch(parser_s->frame_s.SlaveCmd)
        {
            case SLAVE_CMD_FLASH_START:
                memcpy(&flash_s.size, parser_s->frame_s.frame_data, 4);
                if(flash_s.size == 0 || flash_s.size > FLASH_SIZE)
                {
                    error_code = 0x00;
                    frame_s.frame_data = &error_code;
                    frame_s.FrameDataLen = 1;
                    frame_s.SlaveCmd = SLAVE_CMD_FLASH_START_FAIL;
                }else{
                    SPI_Flash_Erase(flash_s.size);
                    flash_s.write_pos = 0;
                    frame_s.SlaveCmd = SLAVE_CMD_FLASH_START_SUCCESS;
                }

            break;
            case SLAVE_CMD_FLASH_TRANS:
                SPI_Flash_Write_NoCheck(parser_s->frame_s.frame_data,flash_s.write_pos,parser_s->frame_s.FrameDataLen);
                flash_s.write_pos += parser_s->frame_s.FrameDataLen;
                frame_s.SlaveCmd = SLAVE_CMD_FLASH_TRANS_SUCCESS;
            break;    
            case SLAVE_CMD_FLASH_CRC:
                frame_s.SlaveCmd = SLAVE_CMD_FLASH_CRC_SUCCESS;
            break;                        
            default:
            frame_s.SlaveCmd = SLAVE_CMD_FLASH_ERROR;
            break;
        }
    }

    creat_send_cmd(&frame_s);
}